<template>
  <div class="wrapper">
    <el-alert title="添加商品信息" type="info" show-icon center> </el-alert>
    <!-- 步骤条 -->
    <el-steps :active="active" align-center finish-status="success">
      <el-step title="基本信息"></el-step>
      <el-step title="商品参数"></el-step>
      <el-step title="商品属性"></el-step>
      <el-step title="商品图片"></el-step>
      <el-step title="商品内容"></el-step>
      <el-step title="完成"></el-step>
    </el-steps>
    <!-- 标签页 -->
    <el-tabs
      tabPosition="left"
      style="height: 100%"
      @tab-click="handleClick"
      v-model="active"
    >
      <el-tab-pane label="基本信息" name="0" :model="model">
        <el-form :rules="rules" label-width="100px">
          <el-form-item label="商品名称" prop="goods_name">
            <el-input v-model="model.goods_name" />
          </el-form-item>
          <el-form-item label="商品价格" prop="goods_price">
            <el-input v-model="model.goods_price" />
          </el-form-item>
          <el-form-item label="商品重量" prop="goods_weight">
            <el-input v-model="model.goods_weight" />
          </el-form-item>
          <el-form-item label="商品数量" prop="goods_number">
            <el-input v-model="model.goods_number" />
          </el-form-item>
        </el-form>

        <el-form
          :rules="rule1"
          label-width="100px"
          ref="ruleRef"
          :model="pidmodel"
        >
          <el-form-item label="选择商品分类:" prop="goods_cat">
            <el-cascader
              @change="getList"
              v-model="pidmodel.goods_cat"
              :options="Categories"
              :props="{
                expandTrigger: 'hover',
                value: 'cat_id',
                label: 'cat_name',
              }"
            ></el-cascader>
          </el-form-item>
        </el-form>
      </el-tab-pane>

      <el-tab-pane label="商品参数" name="1">
        <div v-for="tag in manyTableData" :key="tag">
          <h4>{{ tag.attr_name }}</h4>
          <el-radio
            label="1"
            border
            v-for="(item, index) in tag.attr_vals"
            :key="index"
            >{{ item }}</el-radio
          ><br />
        </div>
      </el-tab-pane>

      <el-tab-pane label="商品属性" name="2">
        <div v-for="tag in onlyTableData" :key="tag">
          <h4>{{ tag.attr_name }}</h4>
          <el-input v-model="tag.attr_vals"></el-input><br /><br /></div
      ></el-tab-pane>

      <el-tab-pane label="商品图片" name="3">
        <!-- 上传图片 -->
        <el-upload
          class="upload-demo"
          action="https://jsonplaceholder.typicode.com/posts/"
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          :before-remove="beforeRemove"
          multiple
          :limit="3"
          :on-exceed="handleExceed"
          :file-list="fileList"
        >
          <el-button size="small" type="primary">点击上传</el-button>
        </el-upload>
      </el-tab-pane>
      <el-tab-pane label="商品内容" name="4">
        <el-button type="primary" @click="getAddGoods()">添加内容</el-button>
        <div id="richText" style="height: 400px; background-color: #fff"></div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import { reactive, toRefs, ref, onMounted, computed } from "vue";
import api from "@/http/goods.js";
import E from "wangeditor";
import { ElMessageBox, ElMessage } from "element-plus";
import { useRoute, useRouter } from "vue-router"; /** 引入router*/

export default {
  name: "add",
  setup() {
    const phoneEditor = ref("");
    /**
     * 路由
     */
    let router = useRouter();
    /**
     * 下一步
     */
    const ruleRef = ref();
    let handleClick = ({ props }) => {
      console.log(props.name, "props");
      if (props.name !== "0") {
        ruleRef.value.validate((valid) => {
          if (valid) {
            if (props.name == "1") {
              state.activeName = "many";
              getList();
            }
            if (props.name == "2") {
              state.activeName = "only";
              getList();
            }
          } else {
            state.active = "0"; //
            ElMessage.error("请选择商品分类");
            return false;
          }
        });
      }
    };
    /**
     * 定义数据
     */
    const state = reactive({
      // 动态参数的数据
      manyTableData: [],
      // 静态属性的数据
      onlyTableData: [],
      //分类数据id
      selectedCateKeys: [],

      activeName: "many",
      /**
       * 步骤条步骤
       */
      active: "0",
      /**
       * 表单验证规则
       */
      rules: {
        goods_name: [
          {
            message: "请输入商品名称",
            trigger: "blur",
          },
        ],
        goods_price: [
          {
            message: "请输入商品价格",
            trigger: "blur",
          },
        ],
        goods_weight: [
          {
            message: "请输入商品重量",
            trigger: "blur",
          },
        ],
        goods_number: [
          {
            message: "请输入商品数量",
            trigger: "blur",
          },
        ],
      },
      rule1: {
        goods_cat: {
          required: true,
          message: "请输入商品分类",
          trigger: "blur",
        },
      },
      /**
       * 添加模型
       */
      pidmodel: {},
      model: {},
      /**
       * 分类参数
       */
      Categories: [],
      /**
       * 用户模型
       */
      list: [],
    });
    /**
     * 获取参数
     */
    let getList = async () => {
      console.log(199, state.pidmodel.goods_cat);
      const res = await api.AttributeList(
        state.pidmodel.goods_cat[2],
        state.activeName
      );
      console.log("参数列表", res);
      if (res.meta.status === 200) {
        res.data.forEach((item) => {
          item.attr_vals = item.attr_vals
            ? item.attr_vals.split(" ").filter((c) => c)
            : [];
        });
        console.log(res.data);
        state.manyTableData = res.data;
        state.onlyTableData = res.data;
        console.log(state.onlyTableData);
      }
    };
    /**
     * 获取分类数据
     */
    let getCategories = async () => {
      const res = await api.CategoriesList();
      console.log(res);
      if (res.meta.status == 200) {
        state.Categories = res.data;
      }
    };
    /**
     * 添加用户
     */
    let getAddGoods = async () => {
      var obj = {
        ...state.model,
        goods_cat: state.pidmodel.goods_cat.join(","),
        pics: [],
      };
      console.log(obj,'obj');
      const res = await api.AddGoods(obj);
      if (res.meta.status == 201) {
        router.push({ name: "goods" });
      }
    };

    let catId = computed(() => {
      console.log(state.pidmodel.goods_cat);
      if (state.pidmodel.goods_cat.length === 3) {
        return state.pidmodel.goods_cat[2];
      }
      return null;
    });
    onMounted(() => {
      getCategories();

      phoneEditor.value = new E("#richText");
      // 上传图片到服务器，base64形式
      phoneEditor.value.config.uploadImgShowBase64 = true;
      // 隐藏网络图片
      phoneEditor.value.config.showLinkImg = false;
      // 创建一个富文本编辑器
      phoneEditor.value.create();
      // 富文本内容
      phoneEditor.value.txt.html();
    });
    return {
      ...toRefs(state),
      ruleRef,
      catId,
      router,
      getCategories, //获取分类事件
      handleClick, //下一步 事件
      getAddGoods,
      getList, //获取参数
    };
  },
};
</script>

<style lang="scss" scoped>
#richText {
  margin-top: 10px;
}
.el-steps {
  margin-top: 20px;
}
.el-tabs {
  margin-top: 30px;
}
.el-radio {
  margin-left: 10px;
  margin-top: 5px;
}
</style>